/**
 * @file list.cpp
 * @author ThomasKingFree (dulu150@126.com)
 * @brief
 * @version 0.1
 * @date 2021-05-09
 *
 * @copyright Copyright (c) 2021
 *
 */

#include "utils/list.h"

#include "utils/gui_dfx.h"

namespace YueGUI {
namespace TinyStd {
Vector::Vector(int size) {
    using Ptr = void *;
    data_ = new Ptr[size];
    Dfx::Assert(data_ != nullptr);
    for (int32_t i = 0; i < size; i++) {
        data_[i] = nullptr;
    }
}

Vector::~Vector() {
    if (data_ != nullptr) {
        delete[] data_;
    }
}

bool Vector::Add(void *node) {
    Dfx::Assert(node != nullptr);
    if (tail_ >= size_) {
        return false;
    }

    for (int32_t index = 0; index < size_; index++) {
        if (data_[index] == node) {
            return false;
        }
    }

    if (data_[tail_] != nullptr) {
        return false;
    } else {
        data_[tail_] = node;
        tail_++;
		return true;
    }
}

bool Vector::Remove(void *node) {
    Dfx::Assert(node != nullptr);
    uint8_t pos = size_;
    for (uint8_t index = 0; index < size_; index++) {
        if (data_[index] == node) {
            pos = index;
            break;
        }
    }

    if (pos >= size_) {
        return false;
    } else {
        data_[pos] = nullptr;
    }

    for (uint8_t index = pos; index < size_ - 1; index++) {
        data_[index] = data_[index + 1];
        data_[index + 1] = nullptr;
    }
    tail_--;
    Dfx::Assert(tail_ >= 0);
	return true;
}

bool Vector::Insert(void *node, void *next) {
    Dfx::Assert(node != nullptr);
    if (tail_ >= size_) {
        return false;
    }

    uint8_t pos = size_;
    for (uint8_t index = 0; index < size_; index++) {
        if (data_[index] == node) {
            pos = index;
            break;
        }
    }

    if (pos >= size_) {
        return false;
    } else {
        for (uint8_t index = tail_ + 1; index > pos + 1; index--) {
            data_[index] = data_[index - 1];
        }
        data_[pos + 1] = next;
        tail_++;
		return true;
    }
}

bool Vector::Clear() {
	if (size_ == 0) {
		return false;
	}

    for (uint8_t index = 0; index < size_; index++) {
        data_[index] = nullptr;
    }
	return true;
}
} // namespace TinyStd
} // namespace YueGUI
